﻿using System;
using System.Linq;
using Awesomium.Core;
using System.Diagnostics;
using System.Windows.Forms;

namespace WebControlSample
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main( string[] args )
        {
            // Checks if this is a child rendering process and if so,
            // transfers control of the process to Awesomium.
            if ( WebCore.IsChildProcess )
            {
                WebCore.ChildProcessMain();

                // When our process is not used any more, exit it.
                return;
            }

            // Force single instance application.
            SingleInstance.Make( SecondInstance );

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault( false );

            // Set some initialization settings.
            WebCoreConfig webConfig = new WebCoreConfig()
            {
                SaveCacheAndCookies = true,
                HomeURL = "http://www.google.com",
                LogLevel = LogLevel.Verbose
            };

            // Using our executable as a child rendering process, is not
            // available when debugging in VS.
            if ( !Process.GetCurrentProcess().ProcessName.EndsWith( "vshost" ) )
                // We demonstrate using our own executable as child rendering process.
                webConfig.ChildProcessPath = WebCoreConfig.CHILD_PROCESS_SELF;

            WebCore.Initialize( webConfig );

            Application.Run( new MainForm() );
        }

        private static void SecondInstance( object obj )
        {
            var forms = Application.OpenForms.OfType<MainForm>();

            if ( forms.Count() > 0 )
                forms.First().BeginInvoke( (Action<MainForm>)RestoreMainForm, forms.First() );
        }

        private static void RestoreMainForm( MainForm mainForm )
        {
            if ( mainForm.WindowState == FormWindowState.Minimized )
                mainForm.WindowState = FormWindowState.Normal;

            mainForm.Focus();
            mainForm.OpenTab();
        }
    }
}
